package yannan.voiplock4ble.task;

import org.greenrobot.eventbus.EventBus;

import java.util.List;

import yannan.voiplock4ble.base.MyApplication;
import yannan.voiplock4ble.bean.CommonResponse;
import yannan.voiplock4ble.bean.LocalDBTime;
import yannan.voiplock4ble.bean.LocalDBTimeDao;
import yannan.voiplock4ble.bean.LockKeyBean;
import yannan.voiplock4ble.db.DaoUtils;
import yannan.voiplock4ble.db.MyDBHelper;
import yannan.voiplock4ble.db.daomanager.LocalTimeDaoManager;
import yannan.voiplock4ble.db.daomanager.LockKeyDaoManager;
import yannan.voiplock4ble.net.NetUtils;
import yannan.voiplock4ble.net.base.NetworkCallBack;
import yannan.voiplock4ble.utils.LogUtils;

/**
 * 说明：对比时间的线程 用以判断是否需要从网络下载最新的数据
 * 作者：mainTel
 * 时间：2016/12/1 16:01
 * 备注：
 */
public class CompareTimeTask extends Thread {

    public static int TYPE_VEIN = 2;
    public static int TYPE_PWD = 3;
    public static int TYPE_RECORD = 1;

    int type;
    String lockserialId;

    public static CompareTimeTask create(String lockserialId, int type) {
        CompareTimeTask compareTimeTask = new CompareTimeTask();
        compareTimeTask.type = type;
        compareTimeTask.lockserialId = lockserialId;
        return compareTimeTask;
    }

    @Override
    public void run() {
        if (MyApplication.getInterface().userBean != null)

            NetUtils.getNetworkService().getNewestRecord(MyApplication.getInterface().userBean.userId,
                    lockserialId, type + "").enqueue(new NetworkCallBack<CommonResponse>() {
                @Override
                public void onSuc(CommonResponse resBody) {
                    comperTime(resBody.returnValue);
                }

                @Override
                public void onFail(String msg) {
                    LogUtils.i("CompareTimeTask失败");
                }
            });

    }

    private void comperTime(String returnValue) {
        String time = "";
        if (returnValue == null) {
            returnValue = "2016-01-01 00:00:00";
        }
        try {
            List<LocalDBTime> bean = DaoUtils.getDao(LocalTimeDaoManager.class).getQueryBuilder()
                    .where(LocalDBTimeDao.Properties.LockserialId.eq(lockserialId))
                    .build().list();
            if (bean.size() == 0) {
                upOrLoadList(returnValue, new LocalDBTime(lockserialId, "0", "0"));
            } else {
                upOrLoadList(returnValue, bean.get(0));
            }
        } catch (Exception e) {
            e.printStackTrace();
            upOrLoadList(returnValue, new LocalDBTime(lockserialId, "0", "0"));
        }
    }

    private void upOrLoadList(final String returnValue, final LocalDBTime bean) {
        String time;
        EventBus.getDefault().post("cancelPwdRefresh");
        if (type == TYPE_VEIN) {
            time = bean.veinKeyTime;
            if (returnValue.compareTo(time) > 0) {
                NetUtils.getNetworkService().getLockUserListBle(lockserialId, MyApplication.getInterface().userBean.userId)
                        .enqueue(new NetworkCallBack<List<LockKeyBean>>() {
                            @Override
                            public void onSuc(List<LockKeyBean> resBody) {
                                MyDBHelper.delLockKeyAll(lockserialId, "0");
                                DaoUtils.getDao(LockKeyDaoManager.class).insertOrReplaceList(resBody);
                                bean.veinKeyTime = returnValue;
                                DaoUtils.getDao(LocalTimeDaoManager.class).insertOrReplace(bean);
                                EventBus.getDefault().post("upDateVeinKey");
                            }

                            @Override
                            public void onFail(String msg) {
                            }
                        });
            } else if (returnValue.compareTo(time) < 0) {
                UpLoadLockKeyTask.create(lockserialId, "0").start();
            } else if (returnValue.compareTo(time) == 0) {
                //不需要刷新，通知swipRefresh。setRefresh（false）
                EventBus.getDefault().post("cancelRefresh");
            }
        } else {
            time = bean.pwdKeyTime;
            if (returnValue.compareTo(time) > 0) {
                NetUtils.getNetworkService().getPasswordList(lockserialId, MyApplication.getInterface().userBean.userId)
                        .enqueue(new NetworkCallBack<List<LockKeyBean>>() {
                            @Override
                            public void onSuc(List<LockKeyBean> resBody) {
                                MyDBHelper.delLockKeyAll(lockserialId, "1");
                                DaoUtils.getDao(LockKeyDaoManager.class).insertOrReplaceList(resBody);
                                bean.pwdKeyTime = returnValue;
                                DaoUtils.getDao(LocalTimeDaoManager.class).insertOrReplace(bean);
                                EventBus.getDefault().post("upDatePwdKey");
                            }

                            @Override
                            public void onFail(String msg) {

                            }
                        });
            } else if (returnValue.compareTo(time) < 0) {
                // TODO: 2016/12/1 本地时间大 说明要上传
                UpLoadLockKeyTask.create(lockserialId, "1").start();
            } else if (returnValue.compareTo(time) == 0) {
                //不需要刷新，通知swipRefresh。setRefresh（false）
                EventBus.getDefault().post("cancelRefresh");

            }
        }
    }
}
